﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace GLDotNet.Toolkit
{
    public class GLFWContext : INativeContext
    {
        GLContextParams contextParams;
        IntPtr window;

        public int VersionMajor
        {
            get { return this.contextParams.VersionMajor; }
        }

        public int VersionMinor
        {
            get { return this.contextParams.VersionMinor; }
        }

        public GLFWContext(GLContextParams contextParams, IntPtr window)
        {
            this.contextParams = contextParams;
            this.window = window;
        }

        public object LoadExtensionFunction<T>(string prefix)
        {
            Type delegateType = typeof(T);

            string name = prefix + delegateType.Name;

            IntPtr proc = GLFW.GetProcAddress(name);

            if (proc == IntPtr.Zero)
                throw new GLDotNetException(string.Format("Failed to load extension function \"{0}\".", name));

            ErrorCode error = GLUtility.GetError();

            if (error != GL.NoError)
                throw new GLDotNetException(string.Format("Loading extension function cased error: {0}", error));

            return Marshal.GetDelegateForFunctionPointer(proc, delegateType);
        }

        public bool MakeCurrent()
        {
            GLFW.MakeContextCurrent(this.window);
            return true;
        }

        public bool SwapBuffers()
        {
            GLFW.SwapBuffers(this.window);
            return true;
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
